package com.yl.chainStore.services.impl.pay


import com.alibaba.fastjson.JSONObject
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper
import com.baomidou.mybatisplus.core.toolkit.Wrappers
import com.yl.chainStore.common.Constants
import com.yl.chainStore.common.enums.Status
import com.yl.chainStore.common.enums.TypeEnum
import com.yl.chainStore.entity.pay.*
import com.yl.chainStore.entity.sick.SickCustomerAccessLog
import com.yl.chainStore.entity.sick.SickMedicalRecords
import com.yl.chainStore.mapper.pay.*
import com.yl.chainStore.mapper.sick.SickCustomerAccessLogMapper
import com.yl.chainStore.mapper.sick.SickMedicalRecordsMapper
import com.yl.chainStore.payrule.item.ItemRuleTypeEnum
import com.yl.chainStore.pojo.vo.pay.*
import com.yl.chainStore.pojo.vo.sick.SickMedicalRecordsDetailToStatusVo
import com.yl.chainStore.services.ICustomerInfoService
import com.yl.chainStore.services.IWebCompanyDeptService
import com.yl.chainStore.services.pay.*
import com.yl.chainStore.services.sick.ISickMedicalRecordsService
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.message.common.MessageType
import com.yl.message.service.ISendMessageService
import com.yl.message.websocket.WebSocketMessageType
import com.yl.message.websocket.WebSocketMessageVo
import com.yl.users.entity.CompanyUser
import com.yl.users.services.ICompanyDeptService
import com.yl.users.services.ICompanyUserService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.*

/**
 * @description :用户订单
 * @author :吴枫
 * @create :2021-06-25 11:32:00
 */
@Service
class PayCustomerOrderServiceImpl(
    private val payCustomerOrderMapper: PayCustomerOrderMapper,
    private val payCustomerOrderDetailMapper: PayCustomerOrderDetailMapper,
    private val sickMedicalRecordsMapper: SickMedicalRecordsMapper,
    private val payCompanyCollectionLogMapper: PayCompanyCollectionLogMapper,
    private val payCustomerCouponsMapper: PayCustomerCouponsMapper,
    private val payCustomerOrderItemDiscountRuleLogMapper: PayCustomerOrderItemDiscountRuleLogMapper,
    private val payCustomerOrderDiscountLogMapper: PayCustomerOrderDiscountLogMapper,
    private val payOrderDetailRefundLogMapper: PayOrderDetailRefundLogMapper,
    private val payOrderRefundLogMapper: PayOrderRefundLogMapper,

    private val payOrderCustomerPayLogMapper: PayOrderCustomerPayLogMapper,
    private val payOrderCustomerPayLogDetailMapper: PayOrderCustomerPayLogDetailMapper,

    private val payCustomerGiftsOfGoldMapper: PayCustomerGiftsOfGoldMapper,
    private val payCustomerOrderMoneyUpdateLogMapper: PayCustomerOrderMoneyUpdateLogMapper,

    private val payCustomerBalanceInLogMapper: PayCustomerBalanceInLogMapper,
    private val payCustomerMoneyFlowMapper:PayCustomerMoneyFlowMapper,

    private val sickCustomerAccessLogMapper:SickCustomerAccessLogMapper,
    private val payCustomerOrderItemOperatorLogMapper:PayCustomerOrderItemOperatorLogMapper,
    private val payCustomerBalanceToMoneyLogMapper:PayCustomerBalanceToMoneyLogMapper,
) : IPayCustomerOrderService {

    companion object {
        private val log = LoggerFactory.getLogger(IPayCustomerOrderService::class.java)
    }

    @Autowired
    private lateinit var iCustomerInfoService: ICustomerInfoService

    @Autowired
    private lateinit var iWebCompanyDeptService: IWebCompanyDeptService

    @Autowired
    private lateinit var iSysCompanyPayItemService: ISysCompanyPayItemService

    @Autowired
    private lateinit var iCompanyDeptService: ICompanyDeptService

    @Autowired
    private lateinit var iSendMessageService: ISendMessageService

    @Autowired
    private lateinit var iCompanyUserService: ICompanyUserService

    @Autowired
    private lateinit var iSickMedicalRecordsService: ISickMedicalRecordsService


    override fun goodsArrive(orderDetailId: Long): ResponseBody {
        // todo 技加工物品到货
        return returnSuccess()
    }

    override fun getOrderInfo(orderId: Long): PayCustomerOrder? {
        log.info("订单管理 ==> 获取订单基本信息 ： orderId:{}", orderId)
        return payCustomerOrderMapper.selectById(orderId)
    }

    override fun getOrderDetails(orderId: Long): MutableList<PayCustomerOrderDetail> {
        return payCustomerOrderDetailMapper.getOrderDetail(orderId)
    }

    override fun getDetailById(detailId: Long): PayCustomerOrderDetail? {
        return payCustomerOrderDetailMapper.selectById(detailId)
    }

    override fun updateOrderInfo(order: CustomerOrderUpdateVo): ResponseBody {
        val orderInfo = payCustomerOrderMapper.selectById(order.id) ?: return returnError(
            ErrorCode.OPERATION_DATA_ERROR,
            "未找到订单，请刷新重试"
        )
        if (order.createTime != null) {
            orderInfo.createTime = order.createTime
            val payLogList = getOrderPayLogList(order.id)
            if(payLogList.isNotEmpty()){
                val payLog = payLogList[0]
                updateOrderPayLogInfo(CustomerPayLogUpdateVo(
                    id = payLog.id,
                    payTime = order.createTime,
                    createUserId = payLog.createUserId,
                    remark = payLog.remark
                ))
            }

        }
        orderInfo.remark = order.remark
        if (order.details != null) {
            for (detail in order.details!!) {
                val orderDetail = payCustomerOrderDetailMapper.selectById(detail.id)
                    ?: return returnError(ErrorCode.OPERATION_DATA_ERROR, "订单明细未找到，请刷新重试")
                orderDetail.doctorId = detail.doctorId
                orderDetail.nurseId = detail.nurseId
                orderDetail.consultantId = detail.consultantId
                orderDetail.netConsultantId = detail.netConsultantId
                payCustomerOrderDetailMapper.updateById(orderDetail)
            }
        }
        payCustomerOrderMapper.updateById(orderInfo)

        return returnSuccess()
    }

    override fun updateOrderOriginalPrice(
        orderId: Long,
        originalPrice: Long?,
        updateType: TypeEnum,
        onlyOriginalPrice: Boolean,
        associatedId: Long,
        list: List<PayCustomerOrderDetail>?,
        createUserId: Long?,
        createTime: Date?,
        amountMoney:Long?
    ): ResponseBody {
        val orderInfo = getOrderInfo(orderId) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND, "未找到订单")
        val payCustomerOrderMoneyUpdateLog = PayCustomerOrderMoneyUpdateLog(
            beforeMoney = orderInfo.originalPrice,
            orderId = orderId,
            updateType = updateType,
            associatedId = associatedId,
        )

        if (createUserId != null) {
            payCustomerOrderMoneyUpdateLog.createUserId = createUserId
        }
        if (createTime != null) {
            payCustomerOrderMoneyUpdateLog.createTime = createTime
        }
        if (orderInfo.originalPrice == 0L) {
            return returnError(ErrorCode.OPERATION_DATA_ERROR, "暂不支持修改原价为0的订单，请联系管理员")
        }


        if (list == null || list.isEmpty()) {
            if (originalPrice == null) {
                return returnError(ErrorCode.OPERATION_DATA_ERROR, "请输入订单金额")
            }
            if (!onlyOriginalPrice) {
                orderInfo.amountMoney = orderInfo.amountMoney - (orderInfo.originalPrice - originalPrice)
            }
            if (originalPrice < orderInfo.amountMoney) {
                return returnError(ErrorCode.OPERATION_DATA_ERROR, "已支付金额超出订单金额")
            }

            val percent = originalPrice.div(orderInfo.originalPrice)
            orderInfo.originalPrice = originalPrice

            val details = getDetailList(orderId)
            for (detail in details) {

                detail.realMoney = detail.realMoney.times(percent)
                detail.realPrice = detail.realPrice.div(detail.number)
                payCustomerOrderDetailMapper.updateById(detail)
            }

        } else {

            //原订单比修改后订单多出的金额
            var updateSumMoney = 0L
            for (detail in list) {
                val orderDetail = payCustomerOrderDetailMapper.selectById(detail.id) ?: return returnError(
                    ErrorCode.DATA_IS_NOT_FIND,
                    "未找到订单明细"
                )
                updateSumMoney += orderDetail.realMoney - detail.realMoney

                payCustomerOrderDetailMapper.updateById(detail)
            }
            orderInfo.originalPrice = orderInfo.originalPrice - updateSumMoney
            if (!onlyOriginalPrice) {
                orderInfo.amountMoney = orderInfo.amountMoney - updateSumMoney
            }
        }
        if(amountMoney != null){
            orderInfo.amountMoney = amountMoney
        }
        payCustomerOrderMoneyUpdateLog.afterMoney = orderInfo.originalPrice
        if (orderInfo.originalPrice == orderInfo.amountMoney) {
            orderInfo.status = Status.END
        }
        payCustomerOrderMapper.updateById(orderInfo)
        payCustomerOrderMoneyUpdateLogMapper.insert(payCustomerOrderMoneyUpdateLog)

        return returnSuccess()
    }

    override fun getOrderLeftJoinSet(order: PayCustomerOrder): ResponseBody {
        order.detailsDoctorNames = getOrderDoctorNameStr(order)
//		 setOrderDoctorNamesStrByOrder(order)
        return returnSuccess()
    }

    override fun getOrderDoctors(orderId: Long): Map<Long, CompanyUser> {
        val order = getOrderInfo(orderId) ?: return mutableMapOf()
        order.details = getOrderDetails(orderId)
        return getOrderDoctors(order)

    }

    override fun getOrderDoctors(order: PayCustomerOrder): Map<Long, CompanyUser> {
        if (order.details == null) {
            order.details = getOrderDetails(order.id)
        }
        val resMap = mutableMapOf<Long, CompanyUser>()
        for (detail in order.details!!) {
            if(detail.doctorId != null){
                val user = iCompanyUserService.getUser(detail.doctorId!!)
                if (user != null) {
                    resMap[user.id] = user
                }
            }


        }
        return resMap
    }

    override fun setOrderDetailUserName(order: PayCustomerOrder) {
       if(order.details != null && order.details!!.isNotEmpty()){
           for(detail in order.details!!){
               if(detail.doctorId != null && detail.doctorId != 0L){
                   val doctor = iCompanyUserService.getUser(detail.doctorId!!)
                   if(doctor != null){
                       detail.doctorName = doctor.realName
                   }
               }
               if(detail.nurseId != null && detail.nurseId != 0L){
                   val nurse = iCompanyUserService.getUser(detail.nurseId!!)
                   if(nurse != null){
                       detail.nurseName = nurse.realName
                   }
               }
               if(detail.consultantId != null && detail.consultantId != 0L){
                   val consultant = iCompanyUserService.getUser(detail.consultantId!!)
                   if(consultant != null){
                       detail.consultantName = consultant.realName
                   }
               }
               if(detail.netConsultantId != null && detail.netConsultantId != 0L){
                   val netConsultant = iCompanyUserService.getUser(detail.netConsultantId!!)
                   if(netConsultant != null){
                       detail.netConsultantName = netConsultant.realName
                   }
               }
           }
       }
    }

    override fun getOrderDoctorNameStr(orderId: Long): String? {
        val users = getOrderDoctors(orderId)
        if (users.isEmpty()) {
            return null
        }
        var resStr = ""
        for ((id, user) in users) {
            resStr = resStr + user.realName + " "
        }
        return resStr
    }

    override fun getOrderDoctorNameStr(order: PayCustomerOrder): String? {
        val users = getOrderDoctors(order)
        if (users.isEmpty()) {
            return null
        }
        var resStr = ""
        for ((id, user) in users) {
            resStr = resStr + user.realName + " "
        }
        return resStr
    }

    override fun getOrderNurses(orderId: Long): Map<Long, CompanyUser> {
        val orderDetail = getOrderDetails(orderId)
        val resMap = mutableMapOf<Long, CompanyUser>()
        for (detail in orderDetail) {
            if (detail.nurseId != null) {
                val user = iCompanyUserService.getUser(detail.nurseId!!)
                if (user != null) {
                    resMap[user.id] = user
                }
            }
        }
        return resMap
    }

    override fun getOrderNurseNameStr(orderId: Long): String? {
        val users = getOrderNurses(orderId)
        if (users.isEmpty()) {
            return null
        }
        var resStr = ""
        for ((id, user) in users) {
            resStr = resStr + user.realName + " "
        }
        return resStr
    }

    override fun addDetail(detail: PayCustomerOrderDetail): ResponseBody {
        log.info("订单管理 ==> 添加订单明细 ： detail:{}", detail)
        payCustomerOrderDetailMapper.insert(detail)
        return returnSuccess()
    }

    override fun delAllDetail(orderId: Long): ResponseBody {
        log.info("订单管理 ==> 清除订单所有明细内容 ： orderId:{}", orderId)
        payCustomerOrderDetailMapper.delete(Wrappers.query<PayCustomerOrderDetail?>().eq("order_id", orderId))
        return returnSuccess()
    }

    override fun delDetail(detailId: Long): ResponseBody {
        // TODO: 2021/7/10
        log.info("订单管理 ==> 删除某个明细 ： detailId:{}", detailId)
        payCustomerOrderDetailMapper.deleteById(detailId)
        return returnSuccess()
    }

    override fun getDetailList(orderId: Long): MutableList<PayCustomerOrderDetail> {
        log.info("订单管理 ==> 获取订单明细列表 ： orderId:{}", orderId)
        val orderDetail = getOrderDetails(orderId)
        setOrderDetailItemInfo(orderDetail)
        return orderDetail
    }



    override fun saveOrderVoToOrder(vo: PayCustomerOrderSaveVo): PayCustomerOrder {
        val order = PayCustomerOrder(
            id = vo.id?:0L,
            customerId = vo.customerId,
            createTime = vo.createTime
        )
        if(vo.originalPrice != null && vo.originalPrice != 0L){
            order.orderManualSumMoney = vo.originalPrice
        }
        if(vo.details != null && vo.details!!.isNotEmpty()){
            val details = mutableListOf<PayCustomerOrderDetail>()
            var discountMoney = 0L
            for(detailVo in vo.details!!){
                val deptItemDetail = iSysCompanyPayItemService.itemDetail(detailVo.itemId, getContext().subCompanyId)
                if (deptItemDetail != null) {
                    val detail = PayCustomerOrderDetail(
                        id = 0L,
                        itemId = detailVo.itemId,
                        typeId = deptItemDetail.typeId,
                        itemName = deptItemDetail.showName,
                        specification = deptItemDetail.specification,
                        unit = deptItemDetail.unit,
                        brand = deptItemDetail.brand,
                        number = detailVo.number,
                        remark = detailVo.remark,
                        doctorId = detailVo.doctorId,
                        nurseId = detailVo.nurseId,
                        toothBit =  detailVo.toothBit,
                        price = deptItemDetail.deptRecommendPrice?:deptItemDetail.recommendPrice,
                        realPrice = detailVo.price,
                        itemPrice = detailVo.price,
                        consultantId = detailVo.consultantId,
                        netConsultantId = detailVo.netConsultantId
                    )
                    if(detail.price != detail.itemPrice){
                        //如果价格不相等，他们就有一个手动折扣
                        order.addPayCustomerOrderItemDiscountRuleLog(
                            PayCustomerOrderItemDiscountRuleLog(
                                id = 0L,
                                orderId = order.id,
                                detailId = detail.id,
                                content = detailVo.remark?:"手动划价",
                                ruleType = ItemRuleTypeEnum.MANUAL_DISCOUNT,
                                ruleId = 101L,
                                discountMoney = detail.price - detail.itemPrice
                            )
                        )
                        discountMoney += detail.price - detail.itemPrice
                    }
                    details.add(detail)
                }

            }
            order.discountMoney = discountMoney
            order.details = details
        }


        return order
    }

    /**
     * 处理部分数据
     * 1，计算一下，订单总额()
     */
    override fun accountingPayCustomerOrder(order: PayCustomerOrder): ResponseBody {
        var orderDetailSumMoney = 0L               //应付金额
        if (order.details != null) {
            for (detail in order.details!!) {
                orderDetailSumMoney += detail.realMoney
            }
        }
        //如果有手动输入的价格，就按手动输入的价格来
        if(order.orderManualSumMoney != null && order.orderManualSumMoney != 0L){
            order.originalPrice = order.orderManualSumMoney!!
        }else{
            order.originalPrice = orderDetailSumMoney
        }
        if(order.originalPrice != orderDetailSumMoney){
//            if(order.details != null){
//                for(d in order.details!!){
//                    d.realMoney = d.realMoney.times(order.originalPrice).div(orderDetailSumMoney)
//                    d.realPrice = d.realMoney.div(d.number)
//                }
//            }
            order.addPayCustomerOrderDiscountLog(
                PayCustomerOrderDiscountLog(
                    id = 0,
                    orderId = order.id,
                    customerId = order.customerId,
                    createUserId = getContext().userId,
                    ruleId = 102L,
                    content = "手动划价",
                    discountMoney = orderDetailSumMoney - order.originalPrice
                )
            )
            order.discountMoney = orderDetailSumMoney - order.originalPrice
        }
        order.orderDetailSumMoney = orderDetailSumMoney

        return returnSuccess()
    }

    override fun setOrderDetailItemInfo(order: PayCustomerOrder) {
        if (order.details != null) {
            setOrderDetailItemInfo(order.details!!)
        }
    }

    override fun setOrderDetailItemInfo(list: List<PayCustomerOrderDetail>) {
        for (detail in list) {
            if (detail.typeId == null || detail.itemName.isNullOrEmpty()) {
                val deptItemDetail = iSysCompanyPayItemService.itemDetail(detail.itemId, getContext().subCompanyId)
                if (deptItemDetail != null) {
                    detail.typeId = deptItemDetail.typeId
                    detail.itemName = deptItemDetail.showName
                    detail.specification = deptItemDetail.specification
                    detail.unit = deptItemDetail.unit
                    detail.brand = deptItemDetail.brand
                }
            }
        }
    }

    override fun setOrderRefund(order: PayCustomerOrder) {
        if (order.details != null) {
            setOrderRefund(order.details!!)
        }
    }

    override fun setOrderGiftOfGoldPay(order: PayCustomerOrder) {
        val selectList = payCustomerGiftsOfGoldMapper.selectList(
            Wrappers.query<PayCustomerGiftsOfGold?>()
                .eq("associate_id", order.id)
                .eq("update_type", TypeEnum.PAY_TYPE_PAY_ORDER.code)
        )
        var useGold = 0L
        for (gold in selectList) {
            useGold += gold.money
        }
        order.useGold = useGold
    }

    override fun setOrderRefund(list: List<PayCustomerOrderDetail>) {
        for (detail in list) {
            detail.refundCount = payOrderDetailRefundLogMapper.selectRefundSumCountByDetailId(detailId = detail.id)
            detail.detailRefundSumMoney =
                payOrderDetailRefundLogMapper.selectRefundSumMoneyByDetailId(detailId = detail.id)
        }
    }

    override fun updateOrder(
        orderId: Long,
        masterUserId: Long?,
        secondaryUserId: Long?,
        remark: String?,
        orderMaualSumMoney:Long?
    ): ResponseBody {
        log.info(
            "订单管理 ==> 修改订单基本信息 ： orderId:{}，masterUserId：{}，" +
                    "secondaryUserId：{}，remark：{}，", orderId, masterUserId, secondaryUserId, remark
        )
        val order =
            payCustomerOrderMapper.selectById(orderId) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND, "未找到订单")

        if(orderMaualSumMoney != null){
            order.orderManualSumMoney = orderMaualSumMoney
        }
        if (masterUserId != null) {
            order.masterUserId = masterUserId
        }
        if (secondaryUserId != null) {
            order.secondaryUserId = secondaryUserId
        }
        if (remark != null) {
            order.remark = remark
        }
        payCustomerOrderMapper.updateById(order)

        return returnSuccess()
    }

    override fun delOrder(orderId: Long): ResponseBody {
        val order = payCustomerOrderMapper.selectById(orderId) ?: return returnError(
            ErrorCode.DATA_IS_NOT_FIND,
            "未找到订单"
        )
        if (order.status != Status.NEW_ADD && order.status != Status.WAIT_PAY ) {
            return returnError(
                ErrorCode.OPERATION_DATA_ERROR,
                "该订单不能删除，请刷新重试"
            )
        }
        payCustomerOrderDetailMapper.delete(
            Wrappers.query<PayCustomerOrderDetail?>().eq(
                "order_id", orderId
            )
        )
        payCustomerOrderMapper.deleteById(orderId)
        if(order.status == Status.WAIT_PAY){
            delOrderDiscountLong(orderId)
        }
        return returnSuccess()
    }

    private fun delOrderDiscountLong(orderId:Long):ResponseBody{
        //优惠记录 -- 整单优惠
        val customerOrderDiscountLogs = getCustomerOrderDiscountLogs(orderId)
        for(customerOrderDiscountLog in customerOrderDiscountLogs){
            payCustomerOrderDiscountLogMapper.deleteById(customerOrderDiscountLog.id)
        }
        //优惠记录 -- 项目优惠
        val itemDiscountRuleLogs = getCustomerOrderItemDiscountLogs(orderId)
        for(itemDiscountRuleLog in itemDiscountRuleLogs){
            payCustomerOrderItemDiscountRuleLogMapper.deleteById(itemDiscountRuleLog.id)
        }
        return returnSuccess()
    }

    override fun delOrderHasPay(orderId: Long): ResponseBody {
        log.info(
            "订单管理 ==> 删除订单 ： orderId:{}", orderId
        )
        val payCustomerOrder =
            getOrderInfo(orderId) ?: return returnError(ErrorCode.OPERATION_DATA_ERROR, "未找到该订单，请刷新重试")

        if(payCustomerOrder.originalPrice != payCustomerOrder.amountMoney){
          //有欠款 清除本章订单的欠款
            iCustomerInfoService.subAmountOwed(payCustomerOrder.customerId,payCustomerOrder.originalPrice - payCustomerOrder.amountMoney,"")
        }

        //付款记录
        val payLogs = getOrderPayLogList(orderId)
        for(payLog in payLogs){
            //付款对应的余额变动记录
            val payOrderMoneyFlows = payCustomerMoneyFlowMapper.selectList(
                QueryWrapper<PayCustomerMoneyFlow?>()
                    .eq("use_type", TypeEnum.PAY_TYPE_PAY_ORDER.code)
                    .eq("associate_id", payLog.id)
            )
            for(payOrderMoneyFlow in payOrderMoneyFlows){
                //订单付款的转回余额，然后删除余额变动记录
                iCustomerInfoService.onlyTopBalance(payCustomerOrder.customerId,payOrderMoneyFlow.money)
                payCustomerMoneyFlowMapper.deleteById(payOrderMoneyFlow.id)
            }
            //付款对应馈赠金
            val payOrderGiftGolds = payCustomerGiftsOfGoldMapper.selectList(
                QueryWrapper<PayCustomerGiftsOfGold?>()
                    .eq("update_type", TypeEnum.PAY_TYPE_PAY_ORDER.code)
                    .eq("associate_id", payLog.id)
            )
            for(payOrderGiftGold in payOrderGiftGolds){
                //馈赠金返回
                iCustomerInfoService.onlyAddGiftsOfGold(payCustomerOrder.customerId,payOrderGiftGold.money)
                payCustomerGiftsOfGoldMapper.deleteById(payOrderGiftGold.id)
            }
            if(payLog.details != null){
                for(payLogDetail in payLog.details!!){
                    //付款对应的充值记录
                    val balanceInLogs = payCustomerBalanceInLogMapper.selectList(
                        QueryWrapper<PayCustomerBalanceInLog?>()
                            .eq("use_type", TypeEnum.PAY_TYPE_BALANCE_ORDER_PAY.code)
                            .eq("associated_top_id", payLogDetail.id)
                    )
                    for(balanceInLog in balanceInLogs){
                        payCustomerBalanceInLogMapper.deleteById(balanceInLog.id)
                    }

                    //充值对应的余额变动记录
                    val balanceInMoneyFlows = payCustomerMoneyFlowMapper.selectList(
                        QueryWrapper<PayCustomerMoneyFlow?>()
                            .eq("use_type", TypeEnum.PAY_TYPE_BALANCE_ORDER_PAY.code)
                            .eq("associate_id", payLogDetail.id)
                    )
                    for(balanceInMoneyFlow in balanceInMoneyFlows){
                        //充值的也退回去
                        iCustomerInfoService.onlySubBalance(payCustomerOrder.customerId,balanceInMoneyFlow.money)
                        payCustomerMoneyFlowMapper.deleteById(balanceInMoneyFlow.id)
                    }
                    payOrderCustomerPayLogDetailMapper.deleteById(payLogDetail.id)
                }
            }
            payOrderCustomerPayLogMapper.deleteById(payLog.id)
        }

        //分院收款记录
        val companyCollectionLogs = payCompanyCollectionLogMapper.selectList(QueryWrapper<PayCompanyCollectionLog?>()
            .eq("order_id",orderId)
        )
        for(companyCollectionLog in companyCollectionLogs){
            payCompanyCollectionLogMapper.deleteById(companyCollectionLog.id)
        }

        //优惠记录 -- 整单优惠
        val customerOrderDiscountLogs = getCustomerOrderDiscountLogs(orderId)
        for(customerOrderDiscountLog in customerOrderDiscountLogs){
            payCustomerOrderDiscountLogMapper.deleteById(customerOrderDiscountLog.id)
        }
        //优惠记录 -- 项目优惠
        val itemDiscountRuleLogs = getCustomerOrderItemDiscountLogs(orderId)
        for(itemDiscountRuleLog in itemDiscountRuleLogs){
            payCustomerOrderItemDiscountRuleLogMapper.deleteById(itemDiscountRuleLog.id)
        }
        // 优惠记录 -- 优惠券（暂未做，所以先不处理）

        //订单下项目的回访
        val customerOrderVisitLogList = getCustomerOrderVisitLogList(payCustomerOrder)
        //todo://是否删除暂不确定


        //退款记录
        val refundLogList = getRefundLogList(orderId)
        for(refundLog in refundLogList){
            //退款时直接退成现金 余额至现金时 余额变动记录
            val refundToMoneyLogs = payCustomerMoneyFlowMapper.selectList(
                QueryWrapper<PayCustomerMoneyFlow?>()
                    .eq("use_type", TypeEnum.PAY_TYPE_ORDER_REFUND_TO_MONEY.code)
                    .eq("associate_id", refundLog.id)
            )
            for(refundToMoneyLog in refundToMoneyLogs){
                //退成现金的也返回余额
                iCustomerInfoService.onlyTopBalance(payCustomerOrder.customerId,refundToMoneyLog.money)
                payCustomerMoneyFlowMapper.deleteById(refundToMoneyLog.id)
            }
            // 余额变现金记录
            val refundBalanceToMoneyLogs = payCustomerBalanceToMoneyLogMapper.selectList(QueryWrapper<PayCustomerBalanceToMoneyLog?>()
                .eq("use_type", TypeEnum.PAY_TYPE_ORDER_REFUND_TO_MONEY.code)
                .eq("associate_id", refundLog.id)
            )
            for(refundBalanceToMoneyLog in refundBalanceToMoneyLogs){
                payCustomerBalanceToMoneyLogMapper.deleteById(refundBalanceToMoneyLog.id)
            }
            //退款至余额 余额变动记录
            val refundToBalanceLogs = payCustomerMoneyFlowMapper.selectList(
                QueryWrapper<PayCustomerMoneyFlow?>()
                    .eq("use_type", TypeEnum.PAY_TYPE_ORDER_REFUND.code)
                    .eq("associate_id", refundLog.id)
            )
            for(refundToBalanceLog in refundToBalanceLogs){
                //订单退至余额的金额也扣除
                iCustomerInfoService.onlySubBalance(payCustomerOrder.customerId,refundToBalanceLog.money)
                payCustomerMoneyFlowMapper.deleteById(refundToBalanceLog.id)
            }
            payOrderDetailRefundLogMapper.delete(QueryWrapper<PayOrderDetailRefundLog?>().eq("refund_order_id",refundLog.id))
            payOrderRefundLogMapper.deleteById(refundLog.id)
        }
        //订单金额修改记录
        val orderMoneyUpdateLogs = payCustomerOrderMoneyUpdateLogMapper.selectList(
            QueryWrapper<PayCustomerOrderMoneyUpdateLog?>().eq(
                "order_id",
                orderId
            )
        )
        for(orderMoneyUpdateLog in orderMoneyUpdateLogs){
            payCustomerOrderMoneyUpdateLogMapper.deleteById(orderMoneyUpdateLog.id)
        }


        //客户订单项目就诊记录
        for(detail in payCustomerOrder.details!!){
            val orderOperatorLogs = payCustomerOrderItemOperatorLogMapper.selectList(
                QueryWrapper<PayCustomerOrderItemOperatorLog?>()
                    .eq("detail_id", detail.id)
            )
            for(orderOperatorLog in orderOperatorLogs){
                payCustomerOrderItemOperatorLogMapper.deleteById(orderOperatorLog.id)
            }
        }

        //删除订单
        payCustomerOrderDetailMapper.delete(QueryWrapper<PayCustomerOrderDetail>().eq("order_id",payCustomerOrder.id))
        payCustomerOrderMapper.deleteById(payCustomerOrder.id)

        return returnSuccess()
    }

    override fun getCustomerOrderDiscountLogs(orderId: Long): MutableList<PayCustomerOrderDiscountLog> {
        return  payCustomerOrderDiscountLogMapper.selectList(QueryWrapper<PayCustomerOrderDiscountLog?>().eq("order_id",orderId))
    }

    override fun getCustomerOrderItemDiscountLogs(orderId: Long): MutableList<PayCustomerOrderItemDiscountRuleLog> {
        return payCustomerOrderItemDiscountRuleLogMapper.selectList(QueryWrapper<PayCustomerOrderItemDiscountRuleLog?>().eq("order_id",orderId))
    }

    override fun getCustomerOrderVisitLogList(order: PayCustomerOrder): MutableList<SickCustomerAccessLog> {
        if(order.details == null){
            order.details = getOrderDetails(order.id)
        }
        val resList = mutableListOf<SickCustomerAccessLog>()
        for(detail in order.details!!){
            resList.addAll(sickCustomerAccessLogMapper.selectList(QueryWrapper<SickCustomerAccessLog?>().eq("order_detail_id",detail.id)))
        }
        return resList
    }

    override fun getRefundLogList(orderId: Long): MutableList<PayOrderRefundLog> {
        val selectList = payOrderRefundLogMapper.selectList(
            QueryWrapper<PayOrderRefundLog?>()
                .eq("order_id", orderId)
        )
        for(refundLog in selectList){
            refundLog.details = payOrderDetailRefundLogMapper.selectList(QueryWrapper<PayOrderDetailRefundLog?>()
                .eq("refund_order_id",refundLog.id)
            )
        }
        return selectList
    }

    override fun getRefundLogDetailList(logId: Long): MutableList<PayOrderDetailRefundLog> {
       return  payOrderDetailRefundLogMapper.selectList(QueryWrapper<PayOrderDetailRefundLog?>()
            .eq("refund_order_id",logId)
        )
    }

    override fun setOrderToPaying(orderId: Long): ResponseBody {
        log.info("订单管理 ==> 订单完成 ： orderId:{}", orderId)
        val order =
            payCustomerOrderMapper.selectById(orderId) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND, "未找到订单")
        if (order.status == Status.END) {
            return returnError(ErrorCode.OPERATION_DATA_ERROR, "订单已被处理")
        }
        order.status = Status.PAYING
        payCustomerOrderMapper.updateById(order)
        return returnSuccess()
    }

    override fun setOrderToEnd(orderId: Long): ResponseBody {
        log.info("订单管理 ==> 订单结束 ： orderId:{}", orderId)
        val order =
            payCustomerOrderMapper.selectById(orderId) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND, "未找到订单")
        order.status = Status.END
        payCustomerOrderMapper.updateById(order)
        return returnSuccess()
    }

    override fun getCustomerMedicalRecord(orderId: Long): SickMedicalRecords? {
        log.info("订单管理 ==> 获取订单对应就诊记录 ： orderId:{}", orderId)
        val payCustomerOrder = payCustomerOrderMapper.selectById(orderId) ?: return null
        return sickMedicalRecordsMapper.selectById(payCustomerOrder.recordId)
    }

    override fun getOrderCompanyCollectionLog(orderId: Long): List<PayCompanyCollectionLog> {
        log.info("订单管理 ==> 获取订单对应收款记录列表 ： orderId:{}", orderId)
        return payCompanyCollectionLogMapper.getList(CompanyCollectionLogSelectVo(orderId = orderId))
    }


    override fun bindCoupons(orderId: Long, couponsId: Long): ResponseBody {
        log.info("订单管理 ==> 绑定优惠卷 ： orderId:{},couponsId:{}", orderId, couponsId)
        val coupons =
            payCustomerCouponsMapper.selectById(couponsId) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND, "未找到该优惠卷")
        if (coupons.orderId != null) {
            return returnError(ErrorCode.OPERATION_DATA_ERROR, "该优惠卷已被其他订单绑定")
        }
        coupons.orderId = orderId
        coupons.flag = Status.ONGOING
        payCustomerCouponsMapper.updateById(coupons)
        return returnSuccess()
    }

    override fun unBindCoupons(orderId: Long, couponsId: Long?): ResponseBody {
        log.info("订单管理 ==> 解绑优惠卷 ： orderId:{},couponsId:{}", orderId, couponsId)
        val updateWrapper = Wrappers.update<PayCustomerCoupons>()
        updateWrapper.eq("order_id", orderId)
        if (couponsId != null) {
            updateWrapper.eq("id", couponsId)
        }
        updateWrapper.set("order_id", null).set("flag", Status.NEW_ADD)
        payCustomerCouponsMapper.update(null, updateWrapper)
        return returnSuccess()
    }

    override fun payOrder(id: Long, paySumMoney: Long, payLog: PayOrderCustomerPayLog): ResponseBody {
        log.info("订单管理 ==> 订单付款 ： id:{},paySumMoney:{}", id, paySumMoney)
        val order = payCustomerOrderMapper.selectById(id) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND, "未找到订单")
        if (order.status != Status.WAIT_PAY && order.status != Status.PAYING) {
            return returnError(
                ErrorCode.OPERATION_DATA_ERROR,
                "订单状态不支持付款，请刷新后重试"
            )
        }

        order.details = getDetailList(id)
        val isPayFirst = order.status == Status.WAIT_PAY
        if (!isPayFirst) {
            payLog.payType = TypeEnum.PAY_ORDER_PAY_LOG_PAY_TYPE_OWE
        }

        //需要付款
        val payMoney = order.originalPrice - order.amountMoney
        //实际付款
        var actualPayment = payMoney


        if (paySumMoney > payMoney) {
            return returnError(
                ErrorCode.OPERATION_DATA_ERROR,
                "支付金额超出订单金额"
            )
        }
        if (paySumMoney >= payMoney) {
            //可以直接付清
            //余额付钱
            order.amountMoney = order.originalPrice
        } else {
            //欠款
            order.amountMoney += paySumMoney
            actualPayment = paySumMoney
            if (isPayFirst) {
                //第一次付款时，欠款添加
                iCustomerInfoService.addAmountOwed(order.customerId, payMoney - actualPayment, order.remark)
            }
        }
        //客户付款
        val pay = iCustomerInfoService.pay(
            order.customerId,
            actualPayment,
            TypeEnum.PAY_TYPE_PAY_ORDER,
            payLog.id,
            order.remark,
            payLog.createTime
        )
        if (pay.bodyIsError()) {
            return pay
        }


        //分院收款
        val collection = iWebCompanyDeptService.collection(
            PayCompanyCollectionLog(
                customerId = order.customerId,
                orderId = order.id,
                needPayment = payMoney,
                actualPayment = actualPayment,
                arrears = payMoney - actualPayment,
                dealUserId = getContext().userId,
                deptId = getContext().subCompanyId,
                companyId = getContext().companyId,
                associateId = payLog.id
            )
        )
        if (collection.bodyIsError()) {
            return collection
        }
        val set = Wrappers.update<PayCustomerOrder?>()
            .eq("id", order.id)
            .set("amount_money", order.amountMoney)
        if (isPayFirst) {
            set.set("first_pay_time", Date())
        }
        //设置实际付款
        payCustomerOrderMapper.update(
            null, set
        )

        if (!isPayFirst) {
            iCustomerInfoService.subAmountOwed(order.customerId, actualPayment, order.remark)
        }


        if (actualPayment == payMoney) {
            setOrderToEnd(order.id)
        } else {
            setOrderToPaying(order.id)
        }
        if (isPayFirst) {
            //添加回访，需多次就诊项目
            iCustomerInfoService.addVisitByOrder(order.customerId, order.deptId, order)
            iCustomerInfoService.addOperatorLogByOrder(order.customerId, order.deptId, order)
            for (detail in order.details!!) {
                if (detail.useStartTime != null) {
                    saveDetailUseStartTime(detail, Date())
                }
            }
            //就诊记录明细改成 付款
            val lastRecordsDetail = iCustomerInfoService.getLastRecordsDetail(order.customerId)
            if (lastRecordsDetail != null) {
                iSickMedicalRecordsService.detailToStatus(
                    SickMedicalRecordsDetailToStatusVo(
                        id = lastRecordsDetail.id,
                        toStatus = Status.ORDER_PAY_END
                    )
                )
            }

            //通知前端刷新侧边栏
            val lastLoginHavePremUsers = iCompanyDeptService.getLastLoginHavePremUsers(
                getContext().subCompanyId,
                Constants.UserPermCode.HAS_CHARGE_ORDER
            )
            val vo = WebSocketMessageVo(
                messageType = WebSocketMessageType.REFRESH_COUNT,
                data = Constants.CountRefresh.HAS_CHARGE_ORDER
            )
            for (u in lastLoginHavePremUsers) {
                iSendMessageService.sendMessageToCompanyUserHaveType(
                    JSONObject(0),
                    JSONObject.toJSON(vo) as JSONObject,
                    MessageType.WEBSOCKET,
                    u.id
                )
            }
        }

        return returnSuccess(actualPayment)
    }

    override fun getOrderPayLogList(id: Long): List<PayOrderCustomerPayLog> {
        val selectList = payOrderCustomerPayLogMapper.selectList(
            Wrappers.query<PayOrderCustomerPayLog?>().eq(
                "order_id", id
            ).orderByDesc("create_time")
        )
        for (payLog in selectList) {
            payLog.details = payOrderCustomerPayLogDetailMapper.selectList(
                Wrappers.query<PayOrderCustomerPayLogDetail>().eq(
                    "pay_log_id", payLog.id
                ).orderByAsc("id")
            )
        }
        return selectList
    }

    override fun getPayLogDetailList(logId: Long): List<PayOrderCustomerPayLogDetail> {
        return payOrderCustomerPayLogDetailMapper.selectList(
            Wrappers.query<PayOrderCustomerPayLogDetail>().eq(
                "pay_log_id", logId
            ).orderByAsc("id")
        )
    }

    override fun updateOrderPayLogInfo(vo: CustomerPayLogUpdateVo): ResponseBody {
        val log = payOrderCustomerPayLogMapper.selectById(vo.id) ?: return returnError(
            ErrorCode.OPERATION_DATA_ERROR,
            "未找到收款记录，请刷新重试"
        )
        log.createTime = vo.payTime

        log.createUserId = vo.createUserId
        log.remark = vo.remark
        if (vo.payList != null) {
            for (detail in vo.payList) {
                val payDetail = payOrderCustomerPayLogDetailMapper.selectById(detail.id)
                    ?: return returnError(ErrorCode.OPERATION_DATA_ERROR, "未找到支付明细，请刷新重试")
                payDetail.payType = detail.payType
                payOrderCustomerPayLogDetailMapper.updateById(payDetail)
            }
        }
        payOrderCustomerPayLogMapper.updateById(log)

        // TODO: 2022/5/10 按理 如果时间改了，一些关联的交易记录之类的也是要跟着改的
        //付款充值记录要改
        val selectList = payOrderCustomerPayLogDetailMapper.selectList(
            Wrappers.query<PayOrderCustomerPayLogDetail?>().eq("pay_log_id", vo.id)
        )

        for (detail in selectList) {
            //充值时间和充值方式修改
            val inLogs = payCustomerBalanceInLogMapper.selectList(
                Wrappers.query<PayCustomerBalanceInLog?>().eq("use_type", TypeEnum.PAY_TYPE_BALANCE_ORDER_PAY.code)
                    .eq("associated_top_id", detail.id)
            )
            for(inLog in inLogs){
                inLog.payType = detail.payType
                inLog.createTime = vo.payTime
                inLog.createUserId = vo.createUserId
                payCustomerBalanceInLogMapper.updateById(inLog)
            }
            //余额变动时间修改 充值加钱
            val flows = payCustomerMoneyFlowMapper.selectList(
                Wrappers.query<PayCustomerMoneyFlow?>().eq("use_type",TypeEnum.PAY_TYPE_BALANCE_ORDER_PAY.code)
                    .eq("associate_id",detail.id)
            )
            for(flow in flows){
                flow.createTime = vo.payTime
                flow.createUserId = vo.createUserId
                payCustomerMoneyFlowMapper.updateById(flow)
            }
        }
        //余额变动时间修改  扣钱
        val flows = payCustomerMoneyFlowMapper.selectList(
            Wrappers.query<PayCustomerMoneyFlow?>().eq("use_type",TypeEnum.PAY_TYPE_BALANCE_ORDER_PAY.code)
                .eq("associate_id",vo.id)
        )
        for(flow in flows){
            flow.createTime = vo.payTime
            flow.createUserId = vo.createUserId
            payCustomerMoneyFlowMapper.updateById(flow)
        }

        val collections = payCompanyCollectionLogMapper.selectList(
            Wrappers.query<PayCompanyCollectionLog?>().eq("type", TypeEnum.COMPANY_COLLECTION_TYPE_ORDER.code)
                .eq("associate_id", vo.id)
        )
        for(collection in collections){
            collection.payTime = vo.payTime
            collection.dealUserId = vo.createUserId
            payCompanyCollectionLogMapper.updateById(collection)
        }

        return returnSuccess()
    }

    override fun updateOrderPayLogAll(payLog: PayOrderCustomerPayLog): ResponseBody {
        val log = payOrderCustomerPayLogMapper.selectById(payLog.id) ?: return returnError(
            ErrorCode.OPERATION_DATA_ERROR,
            "未找到收款记录，请刷新重试"
        )
        payOrderCustomerPayLogMapper.updateById(payLog)
        return returnSuccess()
    }

    override fun payLogToPrint(logId: Long): List<PayOrderPrintShowVo> {
        val payLog = payOrderCustomerPayLogMapper.selectById(logId) ?: return mutableListOf()
        payLog.details = payOrderCustomerPayLogDetailMapper.selectList(
            Wrappers.query<PayOrderCustomerPayLogDetail>().eq(
                "pay_log_id", logId
            ).orderByAsc("id")
        )
        return payLogToPrint(payLog)
    }

    override fun payLogToPrint(payLog: PayOrderCustomerPayLog): List<PayOrderPrintShowVo> {
        if (payLog.details == null) {
            payLog.details = payOrderCustomerPayLogDetailMapper.selectList(
                Wrappers.query<PayOrderCustomerPayLogDetail>().eq(
                    "payLogId", payLog.id
                ).orderByAsc("id")
            )
        }
        val orderInfo = getOrderInfo(payLog.orderId) ?: return mutableListOf()
        val customerInfo = iCustomerInfoService.getById(orderInfo.customerId) ?: return mutableListOf()
        val printShowVo = PayOrderPrintShowVo()
        if (payLog.payType == TypeEnum.PAY_ORDER_PAY_LOG_PAY_TYPE_OWE) {
            printShowVo.title = iWebCompanyDeptService.getOweOrderPrintTitle(payLog.subCompanyId)
            printShowVo.type = TypeEnum.PAY_ORDER_PRINT_TYPE_OWE
        } else {
            printShowVo.title = iWebCompanyDeptService.getOrderPrintTitle(payLog.subCompanyId)
        }
        var paySumMoney = 0L   //付订单的金额
        val payTypeBuffer = StringBuffer() //支付方式（打印用）
        if (payLog.details != null) {
            for (detail in payLog.details!!) {
                paySumMoney += detail.payMoney
                payTypeBuffer.append(detail.payType.typeName + " " + detail.moneyShow + " ")
            }
        }
        printShowVo.amountMoney = paySumMoney
        printShowVo.originalPrice = payLog.originalPrice
        printShowVo.historyNum = customerInfo.historySickNum
        printShowVo.customerName = customerInfo.name
        printShowVo.orderNum = payLog.payNum
        val dept = iCompanyDeptService.getDept(payLog.subCompanyId)
        val user = iCompanyUserService.getUser(payLog.createUserId)
        printShowVo.collectionUserName = user?.realName ?: ""
        printShowVo.doctorNames = getOrderDoctorNameStr(orderInfo.id)
        printShowVo.nurseNames = getOrderNurseNameStr(orderInfo.id)
        printShowVo.payMoneyShow = payTypeBuffer.toString()
        printShowVo.subCompanyPhone = dept?.phone ?: ""
        printShowVo.workTimeShow = iWebCompanyDeptService.getOtherConfigWorkTimeStr(payLog.subCompanyId)
        printShowVo.subCompanyAddress = dept?.address ?: ""
        printShowVo.remark = payLog.remark
//		printShowVo.theCumulativeBalance = payLog.theCumulativeBalance
        printShowVo.theCumulativeBalance = iCustomerInfoService.getCustomerAccount(orderInfo.customerId, getContext().subCompanyId).amountOwed
        // TODO: 2021/12/3 创建时间 是订单的还是付款的
        printShowVo.orderCreateTime = orderInfo.createTime
        printShowVo.printTime = Date()

        val account = iCustomerInfoService.getCustomerAccount(orderInfo.customerId, getContext().subCompanyId)
        printShowVo.balance = account.balance
        printShowVo.giftsOfGold = account.giftsOfGold

        val resList = mutableListOf<PayOrderPrintShowVo>()
        val detailList = getDetailList(orderInfo.id)
        if (detailList.size > 6) {
            var count = (detailList.size / 6)
            if (detailList.size % 6 == 0) {
                count--
            }
            for (i in 0..count) {
                val resVo = printShowVo.copy()
                val fromCount = i * 6
                val toIndex = if ((i + 1) * 6 < detailList.size) {
                    (i + 1) * 6
                } else {
                    detailList.size
                }
                resVo.details = detailList.subList(fromCount, toIndex)
                resList.add(resVo)
            }
        } else {
            printShowVo.details = detailList
            resList.add(printShowVo)
        }
        return resList

    }

    override fun orderAllPayLogToPrint(id: Long): List<PayOrderPrintShowVo> {
        val orderPayLogList = getOrderPayLogList(id)
        if (orderPayLogList.isNotEmpty()) {
            if (orderPayLogList.size == 1) {
                payLogToPrint(orderPayLogList[0])
            }
            //第一次付款为蓝本
            val firstPayLog = orderPayLogList[orderPayLogList.size - 1]
            val payLogDetailsMap = mutableMapOf<TypeEnum, PayOrderCustomerPayLogDetail>()
            for (payLog in orderPayLogList) {
                if (payLog.details == null) {
                    continue
                }
                for (detail in payLog.details!!) {
                    if (payLogDetailsMap[detail.payType] == null) {
                        payLogDetailsMap[detail.payType] = detail
                    } else {
                        payLogDetailsMap[detail.payType]!!.payMoney += detail.payMoney
                    }
                }
            }
            firstPayLog.details = mutableListOf()
            for ((type, detail) in payLogDetailsMap) {
                firstPayLog.details!!.add(detail)
            }

            return payLogToPrint(firstPayLog)
        }
        return mutableListOf()
    }

    override fun refundOrder(vo: RefundByOrderVo): ResponseBody {
        //订单查询，验证
        val order = getOrderInfo(vo.orderId) ?: return returnError(
            ErrorCode.DATA_IS_NOT_FIND,
            "未找到该订单，请刷新后重试"
        )
        if (order.status == Status.NEW_ADD || order.status == Status.WAIT_PAY ) {
            return returnError(
                ErrorCode.OPERATION_DATA_ERROR,
                "该订单不支持退款"
            )
        }
        if (order.status != Status.END  ) {
            return returnError(
                ErrorCode.OPERATION_DATA_ERROR,
                "暂不支持欠款订单退款"
            )
        }
        //todo: 馈赠金额退款问题，待确认后处理
        //setOrderGiftOfGoldPay(order)

        var refundSumMoney = 0L
        val refundOrder = PayOrderRefundLog(
            id = 0L,
            orderId = order.id,
            refundMoney = 0L,
        )
        if (vo.refundToMoney) {
            refundOrder.refundType = TypeEnum.ORDER_REFUND_TYPE_TO_MONEY
        } else {
            refundOrder.refundType = TypeEnum.ORDER_REFUND_TYPE_TO_BALANCE
        }
        payOrderRefundLogMapper.insert(refundOrder)
        var detailList: List<PayCustomerOrderDetail>? = null
        if (vo.customerOrderRefundType == TypeEnum.CUSTOMER_ORDER_REFUND_TYPE_ORDER) {
            if (vo.refundMoney == null || vo.refundMoney!! <= 0) {
                return returnError(ErrorCode.OPERATION_DATA_ERROR, "退款金额错误")
            }
            refundSumMoney = vo.refundMoney!!
        } else {
            if (vo.list == null || vo.list!!.size == 0) {
                return returnError(ErrorCode.DATA_IS_NOT_FIND, "请选择退款项目")
            }
            detailList = mutableListOf()
            for (refundDetail in vo.list!!) {
                //退款明细查询，验证
                val detail = payCustomerOrderDetailMapper.selectById(refundDetail.detailId) ?: return returnError(
                    ErrorCode.DATA_IS_NOT_FIND,
                    "未找到订单记录，请刷新重试"
                )
                if (detail.number < refundDetail.count) {
                    return returnError(
                        ErrorCode.OPERATION_DATA_ERROR,
                        "退款数量异常"
                    )
                }
                detail.number = detail.number - refundDetail.count
                detail.realMoney = detail.realMoney - refundDetail.refundMoney
                if(detail.realMoney < 0){
                    return returnError(
                        ErrorCode.OPERATION_DATA_ERROR,
                        "退款金额大于项目金额"
                    )
                }
                if(detail.number != 0){
                    detail.realPrice = detail.realMoney.div(detail.number)
                }else{
                    detail.realPrice = detail.realMoney
                }


                refundSumMoney += refundDetail.refundMoney
                payOrderDetailRefundLogMapper.insert(
                    PayOrderDetailRefundLog(
                        id = 0L,
                        detailId = detail.id,
                        refundOrderId = refundOrder.id,
                        count = refundDetail.count,
                        refundMoney = refundDetail.refundMoney
                    )
                )
                detailList.add(detail)
            }
        }

        refundOrder.refundMoney = refundSumMoney
        if(order.amountMoney < refundSumMoney){
            return returnError(
                ErrorCode.OPERATION_DATA_ERROR,
                "退款金额超出已付金额"
            )
        }

        val updateOrderOriginalPrice = updateOrderOriginalPrice(
            refundOrder.orderId,
            order.originalPrice - refundSumMoney,
            TypeEnum.ORDER_ORIGINAL_PRICE_UPDATE_TYPE_REFUND,
            false,
            refundOrder.id,
            detailList,
            getContext().userId,
            Date(),null
        )

        if (updateOrderOriginalPrice.bodyIsError()) {
            return updateOrderOriginalPrice
        }
        payOrderRefundLogMapper.updateById(refundOrder)


        iCustomerInfoService.onlyAddBalance(
            order.customerId,
            refundSumMoney,
            TypeEnum.PAY_TYPE_ORDER_REFUND,
            "订单退款",
            refundOrder.id
        )
        //todo 待处理，馈赠金相关
        if (vo.refundToMoney) {
            iCustomerInfoService.balanceToMoney(
                order.customerId,
                refundSumMoney,
                TypeEnum.PAY_TYPE_ORDER_REFUND_TO_MONEY,
                TypeEnum.CUSTOMER_PAY_TYPE_MONEY,
                "",
                0L,
                refundOrder.id
            )
        }
        return returnSuccess()
    }

    override fun addPayCustomerOrderItemDiscountRuleLogs(list: List<PayCustomerOrderItemDiscountRuleLog>,orderId: Long): ResponseBody {
        log.info("订单管理 ==> 添加项目优惠记录 ： list:{}", list)

        payCustomerOrderItemDiscountRuleLogMapper.delete(QueryWrapper<PayCustomerOrderItemDiscountRuleLog>()
            .eq("order_id",orderId))
        for (item in list) {
            payCustomerOrderItemDiscountRuleLogMapper.insert(item)
        }
        return returnSuccess()

    }

    override fun addPayCustomerOrderDiscountLog(list: List<PayCustomerOrderDiscountLog>,orderId: Long): ResponseBody {
        payCustomerOrderDiscountLogMapper.delete(Wrappers.query<PayCustomerOrderDiscountLog?>().eq("order_id",orderId))
        for (item in list) {
            payCustomerOrderDiscountLogMapper.insert(item)
        }
        return returnSuccess()
    }

    override fun completeOrder(id: Long): ResponseBody {
        val order =
            payCustomerOrderMapper.selectById(id) ?: return returnError(ErrorCode.OPERATION_DATA_ERROR, "未找到该订单")
        return completeOrder(order)
    }

    override fun completeOrder(order: PayCustomerOrder): ResponseBody {
        if (order.status != Status.NEW_ADD && order.status != Status.WAIT_PAY) {
            return returnError(ErrorCode.OPERATION_DATA_ERROR, "订单已被处理")
        }
        order.status = Status.WAIT_PAY
        order.orderTime = Date()
        payCustomerOrderMapper.updateById(order)
        return returnSuccess()
    }

    override fun orderHaveDetailToEnd(id: Long): ResponseBody {
        payCustomerOrderMapper.selectById(id) ?: return returnError(
            ErrorCode.DATA_IS_NOT_FIND, "未找到订单，请刷新重试"
        )
        if (
            payCustomerOrderDetailMapper.selectCount(
                Wrappers.query<PayCustomerOrderDetail?>().eq("status", Status.END)
            ) == 0
        ) {
            payCustomerOrderMapper.update(
                null,
                UpdateWrapper<PayCustomerOrder>().eq("id", id).set("sick_status", Status.END)
            )
        } else {
            payCustomerOrderMapper.update(
                null,
                UpdateWrapper<PayCustomerOrder>().eq("id", id).set("sick_status", Status.ONGOING)
            )
        }

        return returnSuccess()
    }

    override fun setDetailToEnd(id: Long): ResponseBody {
        val detail = payCustomerOrderDetailMapper.selectById(id) ?: return returnError(
            ErrorCode.DATA_IS_NOT_FIND, "未找到订单项目，请刷新重试"
        )
        return setDetailToEnd(detail)
    }

    override fun setDetailToEnd(detail: PayCustomerOrderDetail): ResponseBody {
        val onlySetDetailToEnd = onlySetDetailToEnd(detail)
        if (onlySetDetailToEnd.bodyIsError()) {
            return onlySetDetailToEnd
        }
        return orderHaveDetailToEnd(detail.orderId!!)
    }

    override fun onlySetDetailToEnd(detail: PayCustomerOrderDetail): ResponseBody {

        if (detail.status != Status.END) {
            payCustomerOrderDetailMapper.update(
                null,
                UpdateWrapper<PayCustomerOrderDetail?>()
                    .eq("id", detail.id)
                    .set("status", Status.END)
            )
        }
        detail.status = Status.END
        return saveDetailUseStartTime(detail, Date())
    }

    override fun saveDetailUseStartTime(detailId: Long, startTime: Date): ResponseBody {
        log.info("订单管理 ==> 订单明细 ==> 设置使用时间 ： detailId:{}，startTime{}", detailId, startTime)
        val detail = payCustomerOrderDetailMapper.selectById(detailId) ?: return returnError(
            ErrorCode.OPERATION_DATA_ERROR, "未找到订单项目"
        )
        return saveDetailUseStartTime(detail, startTime)
    }

    override fun saveDetailUseStartTime(detail: PayCustomerOrderDetail, startTime: Date): ResponseBody {
        payCustomerOrderDetailMapper.update(
            null,
            Wrappers.update<PayCustomerOrderDetail>()
                .eq("id", detail.id)
                .set("use_start_time", startTime)
        )
        return returnSuccess()
    }
}

